package com.wenhui.schoolyardinfo.mine.ui;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.QMUILoadingView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.wenhui.schoolyardinfo.R;
import com.wenhui.schoolyardinfo.base.BaseActivity;
import com.wenhui.schoolyardinfo.base.BaseMvpActivity;
import com.wenhui.schoolyardinfo.callback.RcvOnItemViewClickListener;
import com.wenhui.schoolyardinfo.customview.CommonPopupWindow;
import com.wenhui.schoolyardinfo.login.view.base.IBaseView;
import com.wenhui.schoolyardinfo.manager.InputManager;
import com.wenhui.schoolyardinfo.mine.adapter.SelectTypeAdapter;
import com.wenhui.schoolyardinfo.mine.bean.AuthenticationBean;
import com.wenhui.schoolyardinfo.mine.bean.SelectTypeBean;
import com.wenhui.schoolyardinfo.mine.presenter.MinePresenterImpl;
import com.wenhui.schoolyardinfo.mine.presenter.base.IMinePresenter;
import com.wenhui.schoolyardinfo.mine.view.IAuthenticationDataView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author    : Urasaki
 * e-mail    : 1164688204@qq.com
 * date      : 2019/7/8 9:50
 * introduce : 身份认证Activity
 */

public class AuthenticationActivity extends BaseMvpActivity<IBaseView, MinePresenterImpl> implements IAuthenticationDataView {


    @BindView(R.id.imv_back)
    ImageView imvBack;
    @BindView(R.id.layout_back)
    RelativeLayout layoutBack;
    @BindView(R.id.tev_title)
    TextView tevTitle;
    @BindView(R.id.tev_end)
    TextView tevEnd;
    @BindView(R.id.topbar)
    QMUITopBar topbar;
    @BindView(R.id.tev_name_prompting)
    TextView tevNamePrompting;
    @BindView(R.id.edt_name)
    EditText edtName;
    @BindView(R.id.layout_name)
    RelativeLayout layoutName;
    @BindView(R.id.tev_credential_type_prompting)
    TextView tevCredentialTypePrompting;
    @BindView(R.id.tev_credential_type)
    TextView tevCredentialType;
    @BindView(R.id.layout_credential_type)
    RelativeLayout layoutCredentialType;
    @BindView(R.id.tev_credential_number_prompting)
    TextView tevCredentialNumberPrompting;
    @BindView(R.id.edt_credential_number)
    EditText edtCredentialNumber;
    @BindView(R.id.layout_credential_number)
    RelativeLayout layoutCredentialNumber;
    @BindView(R.id.tev_school_name_prompting)
    TextView tevSchoolNamePrompting;
    @BindView(R.id.edt_school_name)
    EditText edtSchoolName;
    @BindView(R.id.layout_school_name)
    RelativeLayout layoutSchoolName;
    @BindView(R.id.tev_occupational_categories_prompting)
    TextView tevOccupationalCategoriesPrompting;
    @BindView(R.id.tev_occupational_categories)
    TextView tevOccupationalCategories;
    @BindView(R.id.layout_occupational_categories)
    RelativeLayout layoutOccupationalCategories;
    @BindView(R.id.view_bottom)
    View viewBottom;
    private QMUILoadingView loadView;

    private AuthenticationBean authenticationBean;
    private List<SelectTypeBean> selectCredentialTypelList;//证件类别List
    private List<SelectTypeBean> selectOccupationalList;

    private RecyclerView selectTypeRecyclerView;
    private SelectTypeAdapter selectTypeAdapter;

    private LinearLayoutManager layoutManager;

    //Popwindow
    private CommonPopupWindow credentialTypeWindow;
    //Popwindow
    private CommonPopupWindow window;

    private Map<String, String> bodyParams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_authentication);
        ButterKnife.bind(this);

        initData();
        initViews();
    }

    @Override
    protected void initData() {
        authenticationBean = new AuthenticationBean("隆美尔", "身份证", "100100", "上海交通大学", "学生");
        selectCredentialTypelList = new ArrayList<>();
        selectCredentialTypelList.add(new SelectTypeBean("学生证", false));
        selectCredentialTypelList.add(new SelectTypeBean("身份证", false));
        selectCredentialTypelList.add(new SelectTypeBean("取消", false));

        selectOccupationalList = new ArrayList<>();
        selectOccupationalList.add(new SelectTypeBean("学生", false));
        selectOccupationalList.add(new SelectTypeBean("教师", false));
        selectOccupationalList.add(new SelectTypeBean("取消", false));


        loadView = new QMUILoadingView(this);
        loadView.setVisibility(View.GONE);
        loadView.setSize(120);

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.CENTER;
        addContentView(loadView, layoutParams);

        bodyParams = new HashMap<>();
        bodyParams.put("", "");
        bodyParams.put("", "");
        presenter = new MinePresenterImpl(this, this);
//        presenter.getAuthenticationData(bodyParams);
    }

    @Override
    protected void initViews() {
        setTopBar(topbar);

        edtName.setText(authenticationBean.getName());
        edtCredentialNumber.setText(authenticationBean.getCredentialNumber());
        edtSchoolName.setText(authenticationBean.getSchoolName());
        initPopupWindow();
    }

    @Override
    protected MinePresenterImpl initPresenter() {
        return new MinePresenterImpl(this, this);
    }

    private void initPopupWindow() {
        // create popup window
        credentialTypeWindow = new CommonPopupWindow(AuthenticationActivity.this, R.layout.popup_window_release, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {
            @Override
            protected void initViews() {
                View view = getContentView();
                selectTypeRecyclerView = view.findViewById(R.id.select_photos_recycler_view);
                layoutManager = new LinearLayoutManager(AuthenticationActivity.this);
                layoutManager.setOrientation(OrientationHelper.VERTICAL);
                selectTypeRecyclerView.setLayoutManager(layoutManager);
                selectTypeRecyclerView.setItemAnimator(new DefaultItemAnimator());

                selectTypeAdapter = new SelectTypeAdapter(AuthenticationActivity.this);
                selectTypeRecyclerView.setAdapter(selectTypeAdapter);
                selectTypeAdapter.clearData();
                selectTypeAdapter.addAllData(selectCredentialTypelList);
            }

            @Override
            protected void initEvent() {
                selectTypeAdapter.setRcvOnItemViewClickListener(new RcvOnItemViewClickListener() {
                    @Override
                    public void onItemClickListener(int position, View view) {
                        switch (position) {
                            case 0:
                                selectCredentialTypelList.set(0, new SelectTypeBean("学生证", true));
                                selectCredentialTypelList.set(1, new SelectTypeBean("身份证", false));
                                break;
                            case 1:
                                selectCredentialTypelList.set(0, new SelectTypeBean("学生证", false));
                                selectCredentialTypelList.set(1, new SelectTypeBean("身份证", true));
                                break;
                            case 2:
                                showToast("cancel");
                                break;
                            default:
                                break;
                        }
                        credentialTypeWindow.getPopupWindow().dismiss();
                    }
                });
            }

            @Override
            protected void initWindow() {
                super.initWindow();
                PopupWindow instance = getPopupWindow();
                instance.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        lp.alpha = 1.0f;
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        getWindow().setAttributes(lp);
                    }
                });
            }
        };

        // create popup window
        window = new CommonPopupWindow(AuthenticationActivity.this, R.layout.popup_window_release, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {
            @Override
            protected void initViews() {
                View view = getContentView();
                layoutManager = new LinearLayoutManager(AuthenticationActivity.this);
                layoutManager.setOrientation(OrientationHelper.VERTICAL);

                selectTypeRecyclerView = view.findViewById(R.id.select_photos_recycler_view);
                selectTypeRecyclerView.setItemAnimator(new DefaultItemAnimator());
                selectTypeRecyclerView.setLayoutManager(layoutManager);

                selectTypeAdapter = new SelectTypeAdapter(AuthenticationActivity.this);
                selectTypeRecyclerView.setAdapter(selectTypeAdapter);
                selectTypeAdapter.clearData();
                selectTypeAdapter.addAllData(selectOccupationalList);
            }

            @Override
            protected void initEvent() {
                selectTypeAdapter.setRcvOnItemViewClickListener(new RcvOnItemViewClickListener() {
                    @Override
                    public void onItemClickListener(int position, View view) {
                        switch (position) {
                            case 0:
                                selectOccupationalList.set(0, new SelectTypeBean("学生", true));
                                selectOccupationalList.set(1, new SelectTypeBean("教师", false));
                                tevCredentialType.setText(selectOccupationalList.get(position).getType());
                                break;
                            case 1:
                                selectOccupationalList.set(0, new SelectTypeBean("学生", false));
                                selectOccupationalList.set(1, new SelectTypeBean("教师", true));
                                tevCredentialType.setText(selectOccupationalList.get(position).getType());
                                break;
                            case 3:
                                showToast("cancel");
                                break;
                            default:
                                break;
                        }
                        window.getPopupWindow().dismiss();
                    }
                });
            }

            @Override
            protected void initWindow() {
                super.initWindow();
                PopupWindow instance = getPopupWindow();
                instance.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        lp.alpha = 1.0f;
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        getWindow().setAttributes(lp);
                    }
                });
            }
        };

    }

    private void showCredentialTypePopupWindow(View anchorView) {
        PopupWindow mPopupWindow = credentialTypeWindow.getPopupWindow();
        mPopupWindow.setAnimationStyle(R.style.PopupWindowTranslucentTheme);
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_corners_2_blue_a));
        // 设置点击窗口外边窗口消失
        mPopupWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        mPopupWindow.setFocusable(true);

        // 设置popupWindow的显示位置，此处是在手机屏幕底部且水平居中的位置
        mPopupWindow.showAtLocation(anchorView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//        mPopupWindow.showAtLocation(anchorView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 10);

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    private void showPopupWindow(View anchorView) {
        selectTypeAdapter.clearData();
        selectTypeAdapter.addAllData(selectOccupationalList);
        //        View contentView = CommonPopupWindow();
//        mPopupWindow = new PopupWindow(contentView,
//                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
//        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
//        // 设置好参数之后再show
//        int windowPos[] = PopupWindowManager.calculatePopWindowPos(anchorView, contentView);
//        int xOff = 20; // 可以自己调整偏移
//        windowPos[0] -= xOff;
//        mPopupWindow.showAtLocation(anchorView, Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]);

        PopupWindow mPopupWindow = window.getPopupWindow();
        mPopupWindow.setAnimationStyle(R.style.animTranslate);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        // 设置点击窗口外边窗口消失
        mPopupWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        mPopupWindow.setFocusable(true);
//        // 设置popupWindow的显示位置，此处是在手机屏幕底部且水平居中的位置
        mPopupWindow.showAtLocation(anchorView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    @Override
    public void showLoading() {
        loadView.setVisibility(View.VISIBLE);
        loadView.start();
    }

    @Override
    public void hideLoading() {
        loadView.stop();
        loadView.setVisibility(View.GONE);
    }

    @Override
    public void getAuthenticationDataSuccess(String success) {

    }

    @Override
    public void getAuthenticationDataError(String error) {

    }

    @OnClick({R.id.layout_back, R.id.tev_end, R.id.layout_name, R.id.layout_credential_type, R.id.layout_credential_number, R.id.layout_school_name, R.id.layout_occupational_categories})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.tev_end:
                showToast("tev_end");

                break;
            case R.id.layout_name:
                //把EditText光标移到最后
                edtName.setSelection(authenticationBean.getName().length());
                edtName.setFocusable(true);
                edtName.setFocusableInTouchMode(true);
                edtName.requestFocus();
                InputManager.showInput(edtName);
                break;
            case R.id.layout_credential_type:
                edtName.setFocusable(false);
                InputManager.hideInput(edtName);
                edtCredentialNumber.setFocusable(false);
                InputManager.hideInput(edtCredentialNumber);
                edtSchoolName.setFocusable(false);
                InputManager.hideInput(edtSchoolName);
                showCredentialTypePopupWindow(viewBottom);
                break;
            case R.id.layout_credential_number:
                //把EditText光标移到最后
                edtCredentialNumber.setSelection(authenticationBean.getCredentialNumber().length());
                edtCredentialNumber.setFocusable(true);
                edtCredentialNumber.setFocusableInTouchMode(true);
                edtCredentialNumber.requestFocus();
                break;
            case R.id.layout_school_name:
                //把EditText光标移到最后
                edtSchoolName.setSelection(authenticationBean.getSchoolName().length());
                edtSchoolName.setFocusable(true);
                edtSchoolName.setFocusableInTouchMode(true);
                edtSchoolName.requestFocus();
                break;
            case R.id.layout_occupational_categories:
                edtName.setFocusable(false);
                InputManager.hideInput(edtName);
                edtCredentialNumber.setFocusable(false);
                InputManager.hideInput(edtCredentialNumber);
                edtSchoolName.setFocusable(false);
                InputManager.hideInput(edtSchoolName);
                showPopupWindow(viewBottom);
                break;
        }
    }

}
